<template>
    <ul class="category">
      <li
        v-for="sub in Categories"
        :key="sub.id"
      >
      <router-link
        :to="{path: '/detail', query: {id: sub.id}}"
        tag="div"
      >
        <img :src="sub.image" :alt="sub.title">
        <span>{{sub.title}}</span>
        </router-link>
        <van-button type="danger" size="mini" color="#f40" @click="AddTocart(sub)">加入购物车</van-button>
      </li>
  </ul>
</template>

<script>
import Vue from 'vue'
import { mapActions } from 'vuex'
import { Button } from 'vant'
import { getCategory } from '@/api/home.js'

Vue.use(Button)

export default {
  name: 'Category',
  data () {
    return {
      Categories: []
    }
  },
  methods: {
    ...mapActions(['addTocart']),
    AddTocart (product) {
      const { id, title, price, image } = product
      const shopcart = {
        id,
        title,
        price,
        image,
        count: 1
      }
      this.addTocart(shopcart)
    }
  },
  watch: {
    $route: {
      handler: function (newRoute) {
        const id = newRoute.params.id
        getCategory(id).then(data => {
          this.Categories = data.items.list
          this.Categories = this.Categories.filter(item => item.title)
        })
      },
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
 .category {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    li {
      padding-left: 5%;
      padding-right: 5%;
      box-sizing: border-box;
      width: 50%;
      // border: 1px solid #ccc;
      display: flex;
      flex-direction: column;
      text-align: center;
      img {
        width: 100%;
      }
      span {
        display: -webkit-box;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
    }
  }
</style>
